<template>
  <div>
    <p>节流</p>
    <el-button type="primary" id="throttle">函数节流默认 3 秒</el-button>
    <pre>throttle(callback, wait = 3000) {
      let timer = null;
      let startTime;
      return function() {
        const ctx = this;
        const args = arguments;
        const now = +new Date();
        if (startTime && now < startTime + wait) {
          clearTimeout(timer);
          timer = setTimeout(() => {
            startTime = now;
            callback.apply(ctx, args);
          }, wait);
        } else {
          startTime = now;
          callback.apply(ctx, args);
        }
      };
    }</pre>
  </div>
</template>

<script>
  import hljs from 'highlight.js'
  hljs.initHighlightingOnLoad();
export default {
  name: "Throttle",
  // 对象
  props: {},

  data() {
    return {
      name: ""
    };
  },
  watch: {},
  mounted() {
    const callback = () => {
      console.log("节流");
    };
    document
      .querySelector("#throttle")
      .addEventListener("click", this.throttle(callback));
  },
  methods: {
    // 0.1.1/throttle.js
    /**
     *
     * @param {Function} callback 回调函数
     * @param {Number} wait       间隔时间
     *
     * @return {Function} 节流函数
     */
    throttle(callback, wait = 3000) {
      let timer = null;
      let startTime;
      return function() {
        const ctx = this;
        const args = arguments;
        const now = +new Date();
        if (startTime && now < startTime + wait) {
          clearTimeout(timer);
          timer = setTimeout(() => {
            startTime = now;
            callback.apply(ctx, args);
          }, wait);
        } else {
          startTime = now;
          callback.apply(ctx, args);
        }
      };
    },
    function() {}
  }
};
</script>

<style scoped>

</style>
